import { useStore } from 'vuex'
import { computed, onMounted, ref, watch } from 'vue'

export default function (audioRef) {
    const store = useStore()
    const playing = computed(() => store.state.playing)
    const musicPlayList = computed(() => store.state.musicPlayList)
    const currentIndex = computed(() => store.state.currentIndex)

    // 监听音乐播放状态
    watch(playing, (newVal) => {
        if (newVal) {
             audioRef.value.play()
        } else {
            audioRef.value.pause()
        }
    })

    // 播放 暂停
    function togglePlayState() {
        store.commit('setPlaying', !playing.value)
    }
    // 下一首
    function nextPlay() {
        let nextIndex = currentIndex.value + 1

        if (musicPlayList.value.length === 0) return
        if (musicPlayList.value.length === 1) return
        if (musicPlayList.value.length === nextIndex) nextIndex = 0
        store.commit('setCurrentIndex', nextIndex)
    }
    // 上一首
    function prevPlay() {
        let nextIndex = currentIndex.value - 1

        if (musicPlayList.value.length === 0) return
        if (musicPlayList.value.length === 1) return
        if (nextIndex < 0) nextIndex = musicPlayList.value.length
        store.commit('setCurrentIndex', nextIndex)
    }
    // 更换播放模式
    function changeMode() { }
    
    return {
        togglePlayState,nextPlay,prevPlay,changeMode,
    }
}